package code.rocky.consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class ConsumerDemo03 {

    private static Object lock = new Object();

    public static boolean flag = false;

    static List<Integer> shareData = new ArrayList<Integer>();
    static Random random = new Random();
    private volatile static int i = 1;


    public static void main(String[] args) {
        Thread p = new Thread(new Producer(), "producer");
        Thread c = new Thread(new Consumer(), "consumer");
        p.start();
        c.start();

        try {
            p.join();
            c.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程间通信结束");
    }

    static class Producer implements Runnable {

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (i == 10) {
                        break;
                    }
                    if (flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        producer();
                        flag = true;
                        lock.notify();
                    }
                }
            }
        }

        public void producer() {
            shareData.add(random.nextInt());
            System.out.println(Thread.currentThread().getName() + " 线程第 " + i + " 次生产了随机数: " + shareData.get(0));
        }
    }

    static class Consumer implements Runnable {

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (flag) {
                        consumer();
                        flag = false;
                        i++;
                        lock.notify();
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            if (i == 10) {
                                break;
                            }
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }


        public void consumer() {
            System.out.println(Thread.currentThread().getName() + " 线程第 " + i + " 次消费了随机数: " + shareData.get(0));
            shareData.remove(0);
        }
    }
}
